package cc.fs.myproject.RetrofitUtil;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;


import java.io.File;
import java.util.concurrent.TimeUnit;

import cc.fs.myproject.RetrofitUtil.API;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;

/**
 * Created by fostion on 2015/7/27.
 * 创建retrofit对象
 */
public class ApiFactory {

    public static API api;

    public static API getInstance(Context context){
        if(api != null){
            return api;
        }
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setEndpoint(API.baseUrl)
                .setConverter(getGson())
                .setClient(new OkClient(getOkHttpClient(context)))
//                .setRequestInterceptor(requestInterceptor)
                .build();
         api = restAdapter.create(API.class);
        return api;
    }

    public static GsonConverter getGson(){
       Gson gson = new GsonBuilder()
                    .registerTypeAdapterFactory(new ItemTypeAdapterFactory())
                    .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
                    .create();
        return new GsonConverter(gson);
    }

    public static OkHttpClient getOkHttpClient(Context context) {
        File cacheDir = new File(context.getCacheDir(), "Http_Response_Cache");//cache file
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setCache(new Cache(cacheDir, 1024 * 1024 * 10));// 10m cache
        okHttpClient.setConnectTimeout(10, TimeUnit.SECONDS); //10 time out
        okHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);

        return okHttpClient;
    }




}
